package apiv1

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"go-shop-api/internal/validate"
	"go-shop-api/pkg/e"
	"go-shop-api/pkg/serializer"
	"go-shop-api/pkg/zydhlog"
)

//公用方法

// Validators  公共验证
func Validators(err error) *serializer.Response {
	// 获取validator.ValidationErrors类型的errors
	errs, ok := err.(validator.ValidationErrors)
	if !ok {
		// 非validator.ValidationErrors类型错误直接返回
		return serializer.NewResponse(e.InvalidParams, e.TipsOk, fmt.Sprint(err), nil)
	}

	//判断json类型是否正确
	if _, ok := err.(*json.UnmarshalTypeError); ok {
		return serializer.NewResponse(e.ErrorJsonType, e.TipsOk, fmt.Sprint(err), nil)
	}

	// validator.ValidationErrors类型错误则进行翻译
	return serializer.NewResponse(e.InvalidParams, e.TipsOk, e.TipsNil, validate.RemoveTopStruct(errs.Translate(validate.GetValidatorTrans())))
}

// GetUid 获取uid，中间件jwt set的值
func GetUid(c *gin.Context) uint {
	uid, ok := c.Get("uid")
	if !ok {
		zydhlog.Fatal("获取token中的uid失败!")
	}
	return uid.(uint)
}
